<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="140px"
      v-loading="formLoading"
    >
      <el-form-item label="客户名称" prop="customerId">
        <el-select
          v-model="formData.customerId"
          :disabled="formData.customerDefault"
          class="w-1/1"
          filterable
          placeholder="请选择客户"
          @change="handleCustomerChange(formData.customerId)"
        >
          <el-option
            v-for="item in customerList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="运营经理" prop="managerName">
        <el-input readonly v-model="managerName" disabled />
      </el-form-item>
      <el-form-item label="营业状态" prop="runningStatus">
        <el-input readonly v-model="businessStatus" disabled />
      </el-form-item>
      <el-form-item label="统一社会信用代码" prop="socialCrecode">
        <el-input v-model="formData.socialCrecode" placeholder="请输入统一社会信用代码" />
      </el-form-item>
      <el-form-item label="注册地址" prop="registeredAddress">
        <el-input v-model="formData.registeredAddress" placeholder="请输入注册地址" />
      </el-form-item>
      <el-form-item label="法定代表人" prop="legalPerson">
        <el-input v-model="formData.legalPerson" placeholder="请输入法定代表人" />
      </el-form-item>
      <el-form-item label="注册资本" prop="registeredCapital">
        <el-input v-model="formData.registeredCapital" placeholder="请输入注册资本" />
      </el-form-item>
      <el-form-item label="投资性质" prop="investmentType">
        <el-select v-model="formData.investmentType" placeholder="请选择投资性质">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CRM_INVESTMENT_NATURE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="成立日期" prop="registrationTime">
        <el-date-picker
          v-model="formData.registrationTime"
          type="date"
          value-format="x"
          placeholder="选择成立日期"
        />
      </el-form-item>
      <el-form-item label="营业执照" prop="businessLicenseUrl">
        <UploadFile v-model="formData.businessLicenseUrl" />
      </el-form-item>
      <el-form-item label="身份证复印件" prop="idCardUrl">
        <UploadFile v-model="formData.idCardUrl" />
      </el-form-item>
    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="股东信息" name="businessinfoShareholder">
        <BusinessinfoShareholderForm
          ref="businessinfoShareholderFormRef"
          :businessinfo-id="formData.id"
        />
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as CustomerApi from '@/api/crm/customer'
import { getIntDictOptions, DICT_TYPE, getDictObj } from '@/utils/dict'
import { BusinessinfoApi, BusinessinfoVO } from '@/api/crm/businessinfo'
import BusinessinfoShareholderForm from './components/BusinessinfoShareholderForm.vue'

/** CRM 企业工商信息 表单 */
defineOptions({ name: 'BusinessinfoForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const customerList = ref<CustomerApi.CustomerVO[]>([]) // 客户列表的数据
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  customerId: undefined as unknown as number,
  socialCrecode: undefined,
  registeredCapital: undefined,
  investmentType: undefined,
  registrationTime: undefined,
  businessLicenseUrl: undefined,
  idCardUrl: undefined,
  customerDefault: false,
  registeredAddress: undefined,
  legalPerson: undefined
})
const formRules = reactive({
  customerId: [{ required: true, message: '客户不能为空', trigger: 'blur' }],
  socialCrecode: [{ required: true, message: '统一社会信用代码不能为空', trigger: 'blur' }],
  registeredCapital: [{ required: true, message: '注册资本不能为空', trigger: 'blur' }],
  investmentType: [{ required: true, message: '投资性质不能为空', trigger: 'change' }],
  registrationTime: [{ required: true, message: '成立日期不能为空', trigger: 'blur' }],
  businessLicenseUrl: [{ required: true, message: '营业执照不能为空', trigger: 'blur' }],
  registeredAddress: [{ required: true, message: '注册地址不能为空', trigger: 'blur' }],
  legalPerson: [{ required: true, message: '法定代表人不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const managerName = ref() // 运营经理
const businessStatus = ref() // 营业状态

const handleCustomerChange = async (customerId: number) => {
  if (!customerId) {
    managerName.value = ''
    businessStatus.value = ''
    return
  }
  const customer = customerList.value.find<CustomerApi.CustomerVO>((item) => item.id === customerId)
  managerName.value = customer?.ownerUserName
  const businessStatusObj = getDictObj(DICT_TYPE.CRM_BUSINESS_STATUS, customer?.businessStatus)
  businessStatus.value = businessStatusObj?.label ?? ''
}

/** 子表的表单 */
const subTabsName = ref('businessinfoShareholder')
const businessinfoShareholderFormRef = ref()

/** 打开弹窗 */
const open = async (type: string, id?: number, customerId?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id || customerId) {
    formLoading.value = true
    try {
      if (id) {
        formData.value = await BusinessinfoApi.getBusinessinfo(id)
        formData.value.customerDefault = true // 默认客户的选择，不允许变
      } else {
        formData.value.customerId = customerId
        formData.value.customerDefault = true // 默认客户的选择，不允许变
      }
      const res = await CustomerApi.getCustomer(customerId ?? formData.value.customerId)
      managerName.value = res.ownerUserName
      businessStatus.value =
        getDictObj(DICT_TYPE.CRM_BUSINESS_STATUS, res.businessStatus)?.label ?? ''
    } finally {
      formLoading.value = false
    }
  }
  customerList.value = await CustomerApi.getCustomerSimpleList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await businessinfoShareholderFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'businessinfoShareholder'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as BusinessinfoVO
    // 拼接子表的数据
    data.businessinfoShareholders = businessinfoShareholderFormRef.value.getData()
    if (formType.value === 'create') {
      await BusinessinfoApi.createBusinessinfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await BusinessinfoApi.updateBusinessinfo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    customerId: undefined as unknown as number,
    socialCrecode: undefined,
    registeredCapital: undefined,
    investmentType: undefined,
    registrationTime: undefined,
    businessLicenseUrl: undefined,
    idCardUrl: undefined,
    customerDefault: false,
    registeredAddress: undefined,
    legalPerson: undefined
  }
  managerName.value = ''
  businessStatus.value = ''
  formRef.value?.resetFields()
}
</script>
